package com.itbour.web.action.chat;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;

import com.itbour.common.base.BaseAction;
import com.itbour.common.log.ErrorLogger;
import com.itbour.common.util.StringUtils;
import com.itbour.def.MessageCode;
import com.itbour.def.MessageCodeConstants;
import com.itbour.def.MessageType;
import com.itbour.def.SystemConf;

/**
 * copyright   pirate alliance team 2014
 * @author     xuwei
 *
 */
public class ImageAction extends BaseAction
{

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private File image;

	private Map<String,String> resultMap;

	/**
	 *
	 * @return
	 */
	public String upload()
	{
		String tmpfilePath = this.saveImageTemp();
		resultMap = new HashMap<String,String>();
		resultMap.put("filePath", tmpfilePath);
		return SUCCESS;
	}

	/**
	 * 图像保存
	 * @return
	 */
	private String saveImageTemp()
	{
		String imageRootDir = SystemConf.getImageRootDir();
		Date date = new Date();
		DateFormat df1 = new SimpleDateFormat("yyyyMMdd");
		DateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String tmpImagePath = "temp/" + df1.format(date)+ "/" + df2.format(date) + ".jpg";

		File saveFile = new File(StringUtils.linkFilePath(imageRootDir, tmpImagePath));

		if(image == null)
		{
			return "";
		}
		try
		{
			FileUtils.copyFile(image, saveFile);
		}
		catch (IOException e)
		{
			ErrorLogger.log(e, new MessageCode(MessageCodeConstants.E_00000001,MessageType.ERROR), "RegisterAction", e.getMessage());
			return null;
		}
		finally
		{
			image.delete();
		}

		return tmpImagePath;
	}


	/**
	 * @return the image
	 */
	public File getImage()
	{
		return image;
	}

	/**
	 * @param image the image to set
	 */
	public void setImage(File image)
	{
		this.image = image;
	}

	/**
	 * @return the resultMap
	 */
	public Map<String, String> getResultMap()
	{
		return resultMap;
	}

	/**
	 * @param resultMap the resultMap to set
	 */
	public void setResultMap(Map<String, String> resultMap)
	{
		this.resultMap = resultMap;
	}

}
